package org.jeecg.modules.zcgl.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.zcgl.entity.LeaseContractInfo;
import org.jeecg.modules.zcgl.enums.LeaseContractChargeTypeEnum;
import org.jeecg.modules.zcgl.enums.LeaseContractStatusEnum;
import org.jeecg.modules.zcgl.enums.YesNoEnum;
import org.jeecg.modules.zcgl.service.ILeaseContractInfoService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 自动生成账单
 */
@Slf4j
public class AutoGenerateReceivablesJob implements Job {


	@Autowired
	private ILeaseContractInfoService contractInfoService;

	@Override
	public void execute(JobExecutionContext jobExecutionContext) {
		long start = System.currentTimeMillis();
		log.info("自动生成账单开始：" + start);
        LambdaQueryWrapper<LeaseContractInfo> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LeaseContractInfo :: getIzGenerateComplete, YesNoEnum.NO.getStatus());
		queryWrapper.eq(LeaseContractInfo :: getChargeType, LeaseContractChargeTypeEnum.FIXED_PRICING.getStatus());
		queryWrapper.le(LeaseContractInfo :: getNextRentStartTime, "DATE('" + DateUtils.formatDate(DateUtils.DATE_FORMAT) + "')");
		queryWrapper.in(LeaseContractInfo :: getStatus, LeaseContractStatusEnum.TAKE_EFFECT.getStatus(), LeaseContractStatusEnum.RENEW.getStatus());
//		queryWrapper.apply("DATE(next_rent_start_time) <= DATE('" + DateUtils.formatDate(DateUtils.DATE_FORMAT) + "')");

		List<LeaseContractInfo> leaseContractInfos = contractInfoService.list(queryWrapper);
        if (leaseContractInfos != null && leaseContractInfos.size() > 0){
			leaseContractInfos.stream().forEach(receivablesInfo -> {
				try {
					contractInfoService.autoGenerateReceivables(receivablesInfo);
				} catch (Exception e) {
					e.printStackTrace();
					log.info("自动生成账单错误：" + e.getMessage());
				}
			});
			log.info("共计：" + leaseContractInfos.size() + "条数据。");
		}
		long end = System.currentTimeMillis();
		log.info("自动生成账单结束：" + end);
		log.info("自动生成账单耗时：" + (end-start)/1000 + "S");
	}
}
